package cn.xlbweb.sso.controller;

import cn.xlbweb.sso.server.LayuiTable;
import cn.xlbweb.sso.server.ServerResponse;
import cn.xlbweb.sso.service.IServerService;
import cn.xlbweb.sso.utils.DateUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: bobi
 * @date: 2019-03-09 17:32
 * @description:
 */
@RestController
@RequestMapping("server")
public class ServerController {

    @Autowired
    private IServerService iServerService;

    @GetMapping("list")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/server/server-list");
        return modelAndView;
    }

    @PostMapping("list")
    public LayuiTable list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        return iServerService.list(page, limit);
    }

    @GetMapping("session")
    public ModelAndView session(HttpSession session, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> data = new HashMap<>(7);
        data.put("sessionId", session.getId());
        data.put("creationTime", DateUtil.longToDateFormat(session.getCreationTime()));
        data.put("maxInactiveInterval", session.getMaxInactiveInterval() + "秒");
        data.put("lastAccessedTime", DateUtil.longToDateFormat(session.getLastAccessedTime()));
        data.put("invalidSessionTime", DateUtil.longToDateFormat(session.getLastAccessedTime() + 1800000));
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        data.put("browser", userAgent.getBrowser() + "/" + userAgent.getBrowserVersion());
        data.put("operatingSystem", userAgent.getOperatingSystem());
        mv.addAllObjects(data);
        mv.setViewName("/server/server-session");
        return mv;
    }
}
